package models

import (
	"github.com/robfig/revel"
	"github.com/robfig/revel/cache"
	"kaibb/app/utils"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"time"
)

var blogCollection = "Topic"

type Blog struct {
	Id         bson.ObjectId `bson:"_id"`
	Title      string
	Author     int
	Summary    string
	CreateTime time.Time
	UpdateTime time.Time
	Content    string
	KeyWords   string
	Views      int
	ReplyId    string
	Loves      int
	Category   int
	Tag        []string
}

func AddBlog(blog *Blog) error {
	revel.INFO.Printf("Add blog: ", blog)
	summary := utils.GetSummary(blog.Content)
	blog.Id = bson.NewObjectId()
	blog.CreateTime = time.Now()
	blog.Summary = summary
	session, err := mgo.Dial(utils.DbUrl)

	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	c := session.DB(utils.DbName).C(blogCollection)

	c.Insert(blog)

	return nil
}

func Remove(id bson.ObjectId) error {
	session, err := mgo.Dial(utils.DbUrl)

	if err != nil {
		panic(err)
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	c := session.DB(utils.DbName).C(blogCollection)
	c.Remove(bson.M{"_id": id})
	return nil
}
func UpdateBlog(blog *Blog) error {
	revel.INFO.Printf("Update blog: ", blog)
	summary := utils.GetSummary(blog.Content)
	revel.INFO.Printf("blog summary: ", summary)

	session, err := mgo.Dial(utils.DbUrl)

	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	c := session.DB(utils.DbName).C(blogCollection)

	c.Update(bson.M{"_id": blog.Id}, bson.M{"$set": bson.M{"updatetime": time.Now(), "summary": summary, "title": blog.Title, "content": blog.Content}})
	cache.Delete("blog_" + utils.Id2String(blog.Id))
	return nil
}

func GetBlogs() (blog []*Blog) {

	blog = []*Blog{}
	var query bson.M

	session, err := mgo.Dial(utils.DbUrl)
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	c := session.DB(utils.DbName).C(blogCollection)
	query = bson.M{}
	//所有字段名必须小写
	c.Find(query).Sort("-createtime").All(&blog)
	return blog
}

func GetBlog(id bson.ObjectId) (blog *Blog) {
	blog = &Blog{}
	session, err := mgo.Dial(utils.DbUrl)
	if err != nil {
		panic(err)
	}
	defer session.Close()
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	c := session.DB(utils.DbName).C(blogCollection)
	revel.INFO.Printf("Get blog id: %s", id)
	query := bson.M{"_id": id}
	if err := cache.Get("blog_"+utils.Id2String(id), &blog); err != nil {
		revel.INFO.Printf("can't find in cache")
		c.Find(query).One(&blog)
		blog.Content = utils.Markdown2Html(blog.Content)
		go cache.Set("blog_"+utils.Id2String(id), blog, cache.FOREVER)
	} else {
		blog.Views = blog.Views + 1
	}
	return blog
}
